package com.yc.hwc.web.util;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.yc.hwc.web.IndexDo;

@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Resource
	private IndexDo id;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (request.getSession().getAttribute("loginedUser") == null) {
			String accept = request.getHeader("Accept");
			if (accept != null && accept.contains("application/json")) {
				response.setContentType("application/json;charset=utf-8");
				String json = "{'code':%d, 'msg':'%s'}";
				json = String.format(json, 0, "请先登录系统！");
				response.getWriter().append(json);
			} else {
				String uri = request.getRequestURI();
				String qry = request.getQueryString();
				if(qry!=null && qry.isEmpty()==false) {
					uri += "?" + qry;
				}
				request.getSession().setAttribute("savedUri", uri);
				response.sendRedirect(id.buildRedirectPath("/to_login"));
			}
			return false;
		} else {
			return true;
		}
	}

}
